<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="圈子名称" prop="id">
        <el-select
          v-model="queryParams.id"
          placeholder="请选择圈子"
          filterable
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="circle in circleOptions"
            :key="circle.id"
            :label="circle.name"
            :value="circle.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标签" prop="tagIds">
        <el-select v-model="queryParams.tagIds" multiple placeholder="请选择标签" clearable style="width: 200px">
          <el-option
            v-for="tag in tagOptions"
            :key="tag.id"
            :label="tag.tagName"
            :value="tag.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="成员数量 >=" prop="memberCount" class="member-count">
        <el-input
          v-model.number="queryParams.memberCount"
          placeholder="请输入成员数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="帖子数量 >=" prop="postCount" class="post-count">
        <el-input
          v-model.number="queryParams.postCount"
          placeholder="请输入帖子数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="热度分数 >=" prop="heatScore" class="heat-score">
        <el-input
          v-model="queryParams.heatScore"
          placeholder="请输入热度分数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审批状态" prop="approvalStatus" class="approval-status">
        <el-select v-model="queryParams.approvalStatus" placeholder="请选择审批状态" clearable>
          <el-option
            v-for="dict in approval_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['circle:circle:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['circle:circle:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['circle:circle:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['circle:circle:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="circleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="圈子名称" align="center" prop="circleName" />
      <el-table-column label="圈子头像" align="center" prop="circleAvatar" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.circleAvatar" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="圈子描述" align="center" prop="circleDescription" />
      <el-table-column label="圈主用户呢称" align="center" prop="ownerUser" />
      <el-table-column label="等级体系" align="center" prop="systemName" />
      <el-table-column label="成员数量统计" align="center" prop="memberCount" />
      <el-table-column label="帖子数量统计" align="center" prop="postCount" />
      <el-table-column label="热度分数" align="center" prop="heatScore" />
      <el-table-column label="审批状态" align="center" prop="approvalStatus">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.approvalStatus == 1">已通过</el-tag>
          <el-tag type="danger" v-else-if="scope.row.approvalStatus == 2">已拒绝</el-tag>
          <el-tag type="info" v-else>待审核</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)" v-hasPermi="['circle:circle:query']">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['circle:circle:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['circle:circle:remove']">删除</el-button>
          <el-dropdown v-if="scope.row.approvalStatus == 0" trigger="click" v-hasRole="['admin']">
            <el-button link type="success" icon="Check">审批</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleApprove(scope.row, 1)">已通过</el-dropdown-item>
                <el-dropdown-item @click="handleApprove(scope.row, 2)">已拒绝</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改圈子基础信息对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form ref="circleRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="圈子名称" prop="circleName">
              <el-input v-model="form.circleName" placeholder="请输入圈子名称" />
            </el-form-item>
            <el-form-item label="圈子描述" prop="circleDescription">
              <el-input v-model="form.circleDescription" type="textarea" placeholder="请输入内容" />
            </el-form-item>
            <el-form-item label="圈子头像" prop="circleAvatar">
              <image-upload v-model="form.circleAvatar"/>
            </el-form-item>
            <el-form-item label="等级体系" prop="systemName">
              <el-select v-model="form.systemName" placeholder="请选择等级体系" style="width: 100%">
                <el-option
                  v-for="systemName in systemNameOptions"
                  :key="systemName"
                  :label="systemName"
                  :value="systemName"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="标签" prop="tagIds">
              <el-select v-model="form.tagIds" multiple placeholder="请选择标签" style="width: 100%">
                <el-option
                  v-for="tag in tagOptions"
                  :key="tag.id"
                  :label="tag.tagName"
                  :value="tag.id"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="12" v-if="form.systemName">
          <div class="level-info-container">
            <h3>{{ form.systemName }}等级体系信息</h3>
            <el-empty v-if="levelInfo.length === 0" description="暂无等级信息" />
            <el-table v-else :data="levelInfo" style="width: 100%">
              <el-table-column prop="levelName" label="等级名称" align="center" />
              <el-table-column label="等级图标" align="center">
                <template #default="scope">
                  <el-image 
                    style="width: 40px; height: 40px" 
                    :src="scope.row.levelIcon" 
                    fit="contain"
                    :preview-src-list="[scope.row.levelIcon]"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="minPoints" label="最低积分" align="center" />
              <el-table-column prop="maxPoints" label="最高积分" align="center">
                <template #default="scope">
                  {{ scope.row.maxPoints || '无上限' }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Circle">
import { listCircle, getCircle, delCircle, addCircle, updateCircle, approveCircle, getLevelSystemNames } from "@/api/circle/circle";
import { listTag } from "@/api/tag/tag";
import { listLevel } from "@/api/level/level";
import { useRouter } from 'vue-router';
import ImageUpload from "@/components/ImageUpload";
import ImagePreview from "@/components/ImagePreview";

const { proxy } = getCurrentInstance();
const { approval_status } = proxy.useDict('approval_status');
const router = useRouter();

const circleList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const tagOptions = ref([]);
const systemNameOptions = ref([]);
const circleOptions = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: null,  
    tagIds: [],
    memberCount: null,
    postCount: null,
    heatScore: null,
    approvalStatus: null
  },
  rules: {
    circleName: [
      { required: true, message: "圈子名称不能为空", trigger: "blur" }
    ],
    tagIds: [
      { required: true, message: "请至少选择一个标签", trigger: "change" }
    ],
    systemName: [
      { required: true, message: "等级体系不能为空", trigger: "change" }
    ]
  },
  levelInfo: []
});

const { queryParams, form, rules, levelInfo  } = toRefs(data);

/** 查询圈子基础信息列表 */
function getList() {
  loading.value = true;
  listCircle(queryParams.value).then(response => {
    circleList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 获取所有标签列表 */
function getTagList() {
  listTag().then(response => {
    tagOptions.value = response.rows;
  });
}

/** 获取所有等级体系名称 */
function getSystemNameList() {
  getLevelSystemNames().then(response => {
    systemNameOptions.value = response.data;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    circleName: null,
    circleDescription: null,
    circleAvatar: null,
    ownerUser: null,
    memberCount: null,
    postCount: null,
    heatScore: null,
    approvalStatus: null,
    createdBy: null,
    createdTime: null,
    updatedBy: null,
    updatedTime: null,
    deletedFlag: null,
    tagIds: [],
    systemName: null
  };
  proxy.resetForm("circleRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.tagIds = [];
  handleQuery();
}

/** 获取所有圈子列表用于下拉选择 */
function getCircleOptions() {
  listCircle().then(response => {
    if (response.code === 200 && response.rows) {
      circleOptions.value = response.rows.map(circle => ({
        id: circle.id,
        name: circle.circleName || `圈子${circle.id}`
      }));
    } else {
      circleOptions.value = [];
      proxy.$modal.msgError("获取圈子列表失败");
    }
  }).catch(() => {
    circleOptions.value = [];
    proxy.$modal.msgError("获取圈子列表失败");
  });
}

// 在组件挂载时获取标签列表和等级体系名称列表
onMounted(() => {
  getList();
  getTagList();
  getSystemNameList(); 
  getCircleOptions();
});

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getTagList();
  getSystemNameList(); 
  open.value = true;
  title.value = "添加圈子基础信息";
}

/** 详情按钮操作 */
function handleDetail(row) {
  const circleId = row.id || ids.value[0];
  router.push(`/circle/detail/${circleId}`);
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  getTagList();
  getSystemNameList(); 
  const _id = row.id || ids.value
  getCircle(_id).then(response => {
    form.value = response.data;
    if (response.data.tagList && response.data.tagList.length > 0) {
      form.value.tagIds = response.data.tagList.map(tag => tag.id);
    }
    open.value = true;
    title.value = "修改圈子基础信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["circleRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateCircle(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCircle(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除圈子基础信息编号为"' + _ids + '"的数据项？').then(function() {
    return delCircle(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('circle/circle/export', {
    ...queryParams.value
  }, `circle_${new Date().getTime()}.xlsx`)
}

/** 审批按钮操作 */
function handleApprove(row, status) {
  const statusText = status === 1 ? '通过' : '拒绝';
  proxy.$modal.confirm(`是否确认${statusText}圈子"${row.circleName}"的申请？`).then(function() {
    return approveCircle(row.id, status);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess(`审批${statusText}成功`);
  }).catch(() => {});
}

/** 获取特定等级体系下的所有等级 */
function getLevelInfoBySystemName(systemName) {
  if (!systemName) {
    levelInfo.value = [];
    return;
  }
  
  listLevel({ systemName: systemName, levelStatus: 1 }).then(response => {
    levelInfo.value = response.rows;
  });
}

// 监听等级体系变化
watch(form, (newVal) => {
  if (newVal.systemName) {
    getLevelInfoBySystemName(newVal.systemName);
  } else {
    levelInfo.value = [];
  }
}, { deep: true });

getList();
</script>

<style scoped>
.approval-status :deep(.el-select) {
  width: 180px; 
}
.member-count :deep(.el-form-item__label) {
  white-space: nowrap;
  width: auto !important;
  min-width: 100px;
}
.post-count :deep(.el-form-item__label) {
  white-space: nowrap;
  width: auto !important;
  min-width: 100px;
}
.heat-score :deep(.el-form-item__label) {
  white-space: nowrap;
  width: auto !important;
  min-width: 100px;
}
.level-info-container {
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  height: 100%;
  box-sizing: border-box;
}
.level-info-container h3 {
  margin-top: 0;
  margin-bottom: 15px;
  text-align: center;
  color: #409EFF;
}
</style>